#include "RR.h"
#include <stdio.h>
#include <stdlib.h>

/**
 * 函数: calculateTimes
 * 功能: 根据时间片轮转调度算法计算每个进程的完成时间、周转时间和等待时间
 *
 * 参数:
 *  - processes: 指向包含多个进程信息的数组
 *  - n: 进程数量
 *  - time_slice: 时间片长度
 *
 * 描述:
 *  计算进程的完成时间，周转时间和等待时间并存在结构体中即可
 */
void
calculateTimes (Process *processes, int n, int time_slice)
{
  // TODO
  int t = 0, cur = 0, used_time, pending = 1;
  while (pending) {
    if (processes[cur].arrival_time <= t && processes[cur].remaining_time > 0) {
      used_time = processes[cur].remaining_time > time_slice ? time_slice : processes[cur].remaining_time;
      if (processes[cur].remaining_time > time_slice)
        processes[cur].remaining_time -= time_slice;
      else {
        processes[cur].remaining_time = 0;
        processes[cur].completion_time = t + used_time;
        processes[cur].turnaround_time = t + used_time - processes[cur].arrival_time;
      }
    }
    //更新未执行指令的等待时间
    for (int i = 0; i < n; i++) {
      if ((i != cur) && (processes[i].remaining_time > 0)
        && (processes[i].arrival_time <= t + used_time)
      ) {
        if (t < processes[i].arrival_time)
            processes[i].waiting_time += used_time - (processes[i].arrival_time - t);
        else
            processes[i].waiting_time += used_time;
      }
    }
    // 寻找下一个可以执行的进程
    pending = cur;
    do {
      cur = (cur + 1) % n;
    } while (cur != pending && processes[cur].remaining_time == 0);
    //如果遍历完所有的进程都执行完毕，那么循环结束
    pending = cur == pending ? 0 : 1;

    t += used_time;
  }
  return;
}
